package com.tgjorgoski.sidekicknotes.rtfview.support;

import java.awt.event.MouseEvent;
import java.util.List;

import javax.swing.JPopupMenu;
import javax.swing.text.*;
import javax.swing.text.html.HTMLDocument;

import com.tgjorgoski.sidekicknotes.htmlview.HTMLDocChanged;
import com.tgjorgoski.sidekicknotes.htmlview.HTMLEditor;

public class UtilOperationsMenuFiller implements PopupMenuFiller {

	public void populateMenu(JPopupMenu populateThisMenu, MouseEvent e) {
		if (e.getComponent() instanceof HTMLEditor) {
			HTMLEditor htmlEd = (HTMLEditor)e.getComponent();
			int sPosition=htmlEd.getSelectionStart();
			int ePosition=htmlEd.getSelectionEnd();
			if (sPosition==ePosition) return;
			HTMLDocChanged htmlDoc = (HTMLDocChanged)htmlEd.getDocument();


		}
	}
	
	private void sum(HTMLDocChanged htmlDoc, int sPosition, int ePosition) {
		List<Element> paragraphs = htmlDoc.getParagraphs(sPosition, ePosition);
		int sum = 0;
		for (Element para : paragraphs) {
			int sOffset = para.getStartOffset();
			int eOffset = para.getEndOffset();
			int add=0;
			try {
				String parText = htmlDoc.getText(sOffset, eOffset-sOffset);
				add=Integer.parseInt(parText);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			sum+=add;
		}
		//TODO:Add the sum after the last paragraph...
		Element lastPara = paragraphs.get(paragraphs.size()-1);
		int eOffset = lastPara.getEndOffset();
		try {
			htmlDoc.insertString(eOffset, "sum:" + sum + "\n", null);
		} catch (BadLocationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
